import axios from 'axios'
import store from '@/store'
import { Message } from 'element-ui'
import router from '@/router'
const request = axios.create(
  {
    baseURL: process.env.VUE_APP_BASE_API,
    timeout: 5000
  })

request.interceptors.request.use(config => {
  const token = store.state.user.token
  console.log('token', token)
  if (token) {
    config.headers.Authorization = `Bearer ${token}`
  }
  return config
}, error => {
  return Promise.reject(error)
})

// 响应拦截器
request.interceptors.response.use(response => {
  console.log(response)
  if (response.data instanceof Blob) {
    return response.data
  }
  if (response.data.success) {
    return response.data
  } else {
    Message.error(response.data.message)
    return Promise.reject(response.data.message)
  }
}, error => {
  if (error.response.status === 401) {
    Message.error('token失效')
    // 清空本地信息
    store.dispatch('user/logout')
    // 返回登录页
    router.push('/login')
  }
  return Promise.reject(error)
})

export default request
